import * as api from '@/services/ReturnMoneyPlanMgr';
import _ from 'lodash';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import {
  recalculateSupplyDates,
  allStringModifyNumber,
  buildTableData,
  regenerateData,
  setSupplyDatesEdit,
} from '../utils/publicMethod';

dayjs.extend(utc);
dayjs.extend(isSameOrBefore);

// 回款计划编辑字段
const returnMoneyEditKey = [
  'actualSignAmount', // 实际签约金额
  'planSignAmount', // 计划签约金额
  'signAmount', // 签约金额
  'incrementReturnAmountActual', // 实际数-增量回款
  'storeReturnAmountActual', // 实际数-存量回款
  'incrementReturnAmountCalculate', // 测算数-增量回款
  'storeReturnAmountCalculate', // 测算数-存量回款
  'incrementReturnAmountAdjust', // 调整数-增量回款
  'storeReturnAmountAdjust', // 调整数-存量回款
  'signedUnrecovered', // 已签未回
  'refundable', // 期初应退
  'incrementReturnAmount', // 本期回款-增量回款
  'storeReturnAmount', // 本期回款-存量回款
  'totalReturnAmount', // 本期回款-回款合计
  'earlyReceivableAmount', // 本期回款-期初应收
  'finalReceivable', // 本期回款-期末应收
  'receivableAmount', // 本期应收
  'signAmountTotal', // 签约累计金额
  'yearSignAmountTotal', // 签约当年累计金额
  'returnAmountTotal', // 回款累计金额
  'yearReturnAmountTotal', // 回款当年累计金额
  'lastMonthNotReceivableAmount', // 上月应收未收
  'signReturnRate', // 累计签约回款率
  'annualOverallReturnRate', // 年度综合回款率
];

// 全盘概览字段
const ALL_OVERVIEW_KEY = [
  'monthlyReturnedMoney',
  'annualReturnedMoney',
  'nextYearReturnedMoney',
  'residualReceivables',
];

const Model = {
  namespace: 'ReturnMoneyPlanEdit',
  state: {
    all: {},
    affiliationMonth: '', // 版本归属月
    currentYear: '', // 当前年
    currentMonth: '', // 当前月
    endYearMonth: '', // 截止最后不可删除的日期
    latestYearMonth: '', // 最后时间
    earliestYearMonth: '', // 开始时间
    groupsList: [], // 组团列表
    supplyDates: [], // 日期
    preservationList: [], // 提交的容器
    currentVersion: {}, // 版本信息
    treeData: [],
    overallOverviewData: [], // 全盘概览
    currentId: null, // 当前编辑的id
  },
  effects: {
    /* 查询组团列表##########组团下拉框初始数据################ */
    *getGroupsList({ payload }, { call, put }) {
      const response = yield call(api.groupListUsingGET, payload);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        // 版本列表存储起来
        yield put({
          type: 'save',
          payload: { groupsList: response.data },
        });
      }
    },
    // 请求版本信息
    *getVersionsList({ payload }, { call, put }) {
      const { stage, category, version } = payload;
      const params = {
        stageId: stage, // 项目分期id
        versionType: category, // 版本类型
      };
      // 请求版本接口
      const response = yield call(api.returnPlanVersionDataListUsingGET, { params });
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        const currentVersion = _.filter(response.data, x => x.versionId === version);
        // 版本列表存储起来
        yield put({
          type: 'save',
          payload: { currentVersion: _.last(currentVersion) },
        });
      }
    },
    // 查询编辑数据
    *getEditData({ payload, callback }, { call, put }) {
      yield put({
        type: 'save',
        payload: { all: {}, preservationList: [], treeData: [], supplyDates: [], currentId: null },
      });
      const response = yield call(api.editDataListUsingGET, payload);
      if (response && response.code === 1 && !_.isEmpty(response.data)) {
        const { affiliationMonth, voList } = response.data;
        const currentYear = dayjs(affiliationMonth).year();
        const currentMonth = dayjs(affiliationMonth).month() + 1;
        const earliestYearMonth = dayjs(response.data.earliestYearMonth).format('YYYY-MM');
        const latestYearMonth = dayjs(response.data.latestYearMonth).format('YYYY-MM');
        const endYearMonth = latestYearMonth;
        const preservationList = _.cloneDeep(voList);
        // 生成回款计划年月
        const supplyDates = recalculateSupplyDates({
          earliestYearMonth,
          latestYearMonth,
        });
        // 改变所有数值为Number类型
        const newPreservationListNumber = allStringModifyNumber(
          preservationList,
          returnMoneyEditKey,
        );
        // 重新计算
        const buildData = regenerateData(newPreservationListNumber, affiliationMonth);
        const newSupplyDates = setSupplyDatesEdit(supplyDates, buildData);
        // 清洗成表格索要的格式
        const treeData = buildTableData(buildData, affiliationMonth, returnMoneyEditKey);
        // 版本列表存储起来
        yield put({
          type: 'save',
          payload: {
            all: response.data,
            affiliationMonth,
            earliestYearMonth,
            latestYearMonth,
            endYearMonth,
            currentYear,
            currentMonth,
            supplyDates: newSupplyDates,
            lastYear: response.data.latestYearMonth,
            preservationList: buildData,
            treeData,
          },
        });
      }
      if (callback) callback();
    },
    // 请求全盘概览
    *getOverallOverviewData({ payload }, { call, put }) {
      yield put({
        type: 'save',
        payload: { overallOverviewData: [] },
      });
      const res = yield call(api.fullOverviewUsingGET, payload);
      if (res && res.code === 1 && !_.isEmpty(res.data)) {
        // 版本列表存储起来
        yield put({
          type: 'save',
          payload: { overallOverviewData: res.data },
        });
      }
    },
  },
  reducers: {
    // 编辑年
    editYear(state, action) {
      const { supplyDates, preservationList, endYearMonth } = state;
      const { targetKey, actionType } = action.payload;
      let cloneSupplyDates = _.cloneDeep(supplyDates);
      let { latestYearMonth } = state;
      const clonePreservationList = _.cloneDeep(preservationList);
      if (actionType === 'add') {
        // 添加一年
        const soonAddYear = dayjs(state.latestYearMonth).year() + 1;
        latestYearMonth = dayjs(`${soonAddYear}-01`).format('YYYY-MM');
        // 去掉之前的可删除的年
        _.last(cloneSupplyDates).closable = false;
        const monthList = [];
        for (let month = 1; month < 13; month += 1) {
          monthList.push({
            value: month,
            disabled: false,
            error: false,
          });
        }
        // 添加的最后一年可删除
        cloneSupplyDates.push({
          title: soonAddYear,
          closable: true,
          error: false,
          monthList,
        });
        // 新增一年的数据
        const EditKey = {};
        _.forEach(returnMoneyEditKey, key => {
          EditKey[key] = 0;
        });
        _.forEach(clonePreservationList, item => {
          const x = item.detailList;
          for (let month = 1; month < 13; month += 1) {
            x.push({
              ..._.last(item.detailList),
              ...EditKey,
              // signReturnRate: 0,
              // annualOverallReturnRat: 0,
              id: '',
              returnTime: dayjs(`${soonAddYear}-${month}`).format('YYYY-MM-DDTHH:mm:ss'),
              isAllowedDelete: 1,
            });
          }
        });
      }
      if (actionType === 'remove') {
        // 删除掉最后一年
        cloneSupplyDates = _.filter(cloneSupplyDates, x => x.title !== Number(targetKey));
        latestYearMonth = dayjs(`${targetKey - 1}-01`).format('YYYY-MM');
        const maxYear = dayjs(endYearMonth).year();
        if (maxYear < Number(targetKey) - 1) {
          _.last(cloneSupplyDates).closable = true;
        }
        // 删除一年的数据
        _.forEach(clonePreservationList, item => {
          const x = item;
          x.detailList = _.filter(
            item.detailList,
            monthData => !dayjs(targetKey).isSame(monthData.returnTime, 'year'),
          );
        });
      }
      // 重新计算
      const buildData = regenerateData(clonePreservationList, latestYearMonth);
      return {
        ...state,
        supplyDates: cloneSupplyDates,
        preservationList: buildData,
        latestYearMonth,
      };
    },
    // 改变选中的年月
    onChangeYearMonth(state, action) {
      const { key, val } = action.payload;
      if (key === 'currentYear') {
        const currentMonth =
          dayjs(state.earliestYearMonth).year() === _.toNumber(val)
            ? dayjs(state.earliestYearMonth).month() + 1
            : 1;
        const treeData = buildTableData(
          state.preservationList,
          `${val}-${currentMonth}`,
          returnMoneyEditKey,
        );
        return {
          ...state,
          currentYear: val,
          currentMonth,
          treeData,
        };
      }
      const treeData = buildTableData(
        state.preservationList,
        `${state.currentYear}-${val}`,
        returnMoneyEditKey,
      );
      return {
        ...state,
        currentMonth: val,
        treeData,
      };
    },
    // 编辑输入框值
    onChangeVal(state, action) {
      const { modifyAfterData, id } = action.payload;
      const { currentYear, currentMonth, supplyDates } = state;
      const newSupplyDates = setSupplyDatesEdit(supplyDates, modifyAfterData);
      const treeData = buildTableData(
        modifyAfterData,
        `${currentYear}-${currentMonth}`,
        returnMoneyEditKey,
      );
      return {
        ...state,
        preservationList: modifyAfterData,
        treeData,
        currentId: id,
        supplyDates: newSupplyDates,
      };
    },
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
